<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/17
 * Time: 上午9:42
 */

namespace app\index\controller;


use app\common\controller\Balance;
use app\common\controller\Bonus;
use app\common\controller\CardMarke;
use app\common\controller\CreateNotify;
use app\common\controller\Deviceobj;
use app\common\controller\Fenzhang;
use app\common\controller\MachExtend;
use app\common\controller\Platurl;
use app\common\controller\TemplateMsg;
use app\common\model\Agent;
use app\common\model\CardBonusRule;
use app\common\model\CardConsume;
use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardGeneral;
use app\common\model\CardMember;
use app\common\model\CardPaycardlog;
use app\common\model\CardRank;
use app\common\model\CardUserGet;
use app\common\model\CardUserUpdate;
use app\common\model\Merchant;
use app\common\model\OpenTemplate;
use app\common\model\Paylog;
use app\common\model\System;
use app\common\model\WxOpen;
use app\common\model\WxUser;
use think\Controller;
use think\Session;
use Wechat\Wxobjopen;

class Wxnocardpay extends Controller
{


    public function pay()
    {

        $request = request();
        Session::set('openid', null);
        $map['id'] = $request->param('id');
        $Merchant = new Merchant();
        $Agent = new Agent();
        $System = new System();
        $WxOpen = new WxOpen();
        $user = $Merchant->where($map)->find();
        $config = $Agent->where(array('id' => $user['agent']))->find();
        $users = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
            // 'partnerkey'=>$agent['partnerkey']
        );

        $weObj = new Wxobjopen($options);
        $openid = Session::get('openid');
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("wxnocardpay/pay", array('id' => $request->param('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {
                $openid = $info['openid'];
                session('openid', $openid);
                $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $jssdk = $weObj->getJsSign($url);
            }
        }
        $this->assign('jssdk', $jssdk);

        $this->assign("channel", "wxpay");
        $this->assign("headimg", $user['img']);
        $this->assign('mach', $user);
        $this->assign('id', $request->param('id'));
        $this->assign('openid', $openid);
        return $this->fetch();
//        }
    }

    public function pay2()
    {
        $request = request()->param();

        $Paylog = new Paylog();
        $norderid = $Paylog->where(array('orderid' => request()->post('orderid')))->count();
        if ($norderid != 0) {
            $re_param['return_code'] = "FAIL";
            $re_param['return_msg'] = "系统错误,请重试";

        } else {
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $map['id'] = $request['id'];
            $config = $Merchant->where($map)->find();

            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();

            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $weObj = new Wxobjopen($options);
//            $price = request()->post('price');
            $yf_price = request()->post('price');
            $zkarr['merchantid'] = request()->param('id');
            $zkarr['openid'] = request()->post('sub_openid');
            $zkarr['total_fee'] = $yf_price;
            $zkarr['orderid'] = request()->post('orderid');
            //获取门店折扣
            $MachExtend = new MachExtend();
            $res_machzk = $MachExtend->get_machzk($zkarr);
            //已有折扣时将不再调用会员折扣
            $zk_price = 0;
            if ($res_machzk['is_machzk'] == 'Y') {
                $zk_price = $res_machzk['zk_price'];
            }
            $price = $yf_price-$zk_price;
            //END
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no = request()->post('orderid');
            $body = "快捷支付";
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = "";
            $sub_openid = "";

            $total_fee = $price * 100;
            $data['orderid'] = $out_trade_no;
            $data['mid'] = request()->param('id');
//            $data['openid'] = request()->post('openid');
            $data['openid'] = request()->post('sub_openid');
            $data['pay_statu'] = 0;
            $data['price'] = $price;
            $data['yf_price'] = $yf_price;
            $data['zk_price'] = $zk_price;


            $data['add_time'] = time();
            $data['attach'] = request()->post('attach');
            $data['sub_openid'] = "";


            $Paylog = new Paylog();
            $add = $Paylog->save($data);
            $openid = request()->post('sub_openid');
            $notify_url = 'https://' . $_SERVER ['SERVER_NAME'] . '/api.php';
            $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
            $nonce_str = $weObj->generateNonceStr();
            $arrdata = array(
                "appid" => $appid,
                'sub_appid' => $sub_appid,
                "mch_id" => $mch_id,
                "sub_mch_id" => $sub_mch_id,
                "nonce_str" => $nonce_str,
                "body" => $body,
                "out_trade_no" => $out_trade_no,
                "total_fee" => $total_fee,
                "spbill_create_ip" => $spbill_create_ip,
                "notify_url" => $notify_url,
                "openid" => $openid,
                "receipt"=>$config['efp_receipt'],
                'profit_sharing'=>$config['is_profit'],//是否开启分账
                'trade_type' => 'JSAPI'
            );

            $pay_xml = $weObj->createWxPackageXml($arrdata);


            $pay_xml = $weObj->get_pay_id($pay_xml);
            if ($pay_xml['return_code'] == "FAIL") {
                $re_param = $pay_xml;
            } else {
                if ($pay_xml['return_code'] == "SUCCESS") {
                    $prepay_id = $pay_xml['prepay_id'];
                    $jsApiObj["appId"] = $appid;
                    $timeStamp = time();
                    $jsApiObj["timeStamp"] = "$timeStamp";
                    $jsApiObj["nonceStr"] = $nonce_str;
                    $jsApiObj["package"] = "prepay_id=" . $prepay_id;
                    $jsApiObj["signType"] = "MD5";
                    $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
                    $re_param['return_code'] = "SUCCESS";
                    $re_param['return_msg'] = "业务处理成功";
                    $re_param['jsApiObj'] = $jsApiObj;

                } else {
                    $re_param['return_code'] = "FAIL";
                    $re_param['return_msg'] = "配置错误,请联系管理员";
                }
            }

        }
        return json($re_param);
    }

    function payover()
    {
        $request = request();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $request->param('id');
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();

        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );

        $weObj = new Wxobjopen($options);
        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];
        $out_trade_no = $request->param('orderid');
        $nonce_str = $weObj->generateNonceStr();
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = "";
        $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
        $payorder_xml = $weObj->getPayNum($pay_xml);

//        header("Content-type: text/html; charset=utf-8");

        $orderno = $payorder_xml['transaction_id'];
        $pay_zt = $payorder_xml['trade_state'];
        if ($pay_zt == "SUCCESS") {
            $this->order_query($orderno = $payorder_xml['out_trade_no']);
            $data = 0;
        } else {
            $data = 1;
        }

        echo $data;
    }

    public function order_query($orderid)
    {
        $Paylog = new Paylog();
        $mab['orderid'] = $orderid;
        $id = $Paylog->where($mab)->find();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $id['mid'];
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();

        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );

        $weObj = new Wxobjopen($options);
        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];
        $out_trade_no = $orderid;
        $nonce_str = $weObj->generateNonceStr();
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = "";
        $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
        $payorder_xml = $weObj->getPayNum($pay_xml);
        $orderno = $payorder_xml['transaction_id'];
        $pay_zt = $payorder_xml['trade_state'];
        if ($pay_zt == "SUCCESS") {
            $Paylog = new Paylog();
            $data['pay_statu'] = 1;
            $data['orderno'] = $orderno;
            $data['ser_openid'] = $payorder_xml['openid'];
            $data['pay_time'] = date('Y-m-d H:i:s', strtotime($payorder_xml['time_end']));;
            $data['payinfo'] = json_encode($payorder_xml, true);

            $data['sub_openid'] = "";
            $Paylog->save($data, ['orderid' => $payorder_xml['out_trade_no']]);
            $id = $Paylog->where(['orderid' => $payorder_xml['out_trade_no']])->find();
            if ($id['tzzt'] == '0') {
                $s = action('Wxauth/sendtemplate', array($id['mid'], $orderid));
                action('Index/sendprint', array($id));
                $da['tzzt'] = 1;
                $Deviceobj = new Deviceobj();
                $s=$Deviceobj->ylb_sendvoice($payorder_xml['out_trade_no']);
                $da['tzmsg'] = json_encode($s);
                $Paylog->save($da, ['orderid' => $payorder_xml['out_trade_no']]);
                if($config['is_profit']=="Y"){
                    $Fenzhang=new Fenzhang();
                    $Fenzhang->createlog($id);
                }
                $notify_param['merchantid']=$id['mid'];
                $notify_param['out_trade_no']=$id['orderid'];
                $CreateNotify=new CreateNotify();
                $CreateNotify->pay_notify($notify_param);
            }
        }
    }



    //获取topmid
    /*
     * mid
     * */
    private function get_top_mid($arr)
    {
        $Merchant = new Merchant();
        $top_mid = $Merchant->where(['id' => $arr['mid']])->value('top_mid');
        return $top_mid;
    }

    //获取正确的可支付金额
    /*
     * 取小数点后两位四舍五入
     * 舍去时+0.01  舍入时则返回
     * */
    //取支付额
    public function format_price($price)
    {
        $price = (float)$price;//将数值转换为浮点数
        $str = explode(".", $price);//将字符串转换为数组
        if (isset($str[1])) {//判断是否存在小数点
            $str2 = strlen($str[1]);//获取小数点位数
            if ($str2 <= 2) {//当小数点位数小于等于2 原样输出
                $data = $price;
            } else {
                $str4 = substr($str[1], 0, 2);//取出小数点后两位的值
                $str5 = substr($str[1], 0, 1);//取出小数点后1位的值
                if ($str4 == "00") {//当小数点后2为未00时直接+1
                    $str3 = "01";
                } elseif ($str5 == "0") {//当小数点后1为为0时直接最后1位+1
                    if (substr($str[1], 1, 1) + 1 !== 10) {
                        $str3 = (string)$str5 . (substr($str[1], 1, 1) + 1);
                    } else {
                        $str3 = substr($str[1], 0, 1) + 1;
                    }
                } else {//不满足上述条件直接+1
                    $str3 = substr($str[1], 0, 2) + 1;
                }
                if ($str3 == 100) {//当金额为X.99X直接整数+1
                    $data = ($str[0] + 1);
                } else {
                    $data = $str[0] . '.' . $str3;
                }
            }
        } else {
            $data = $price;
        }
        return $data;
    }

    /*余额变动模版消息发送
     * 参数 card_id（会员卡编号），type（变动类型1：充值，2：消费），add_balance（变动余额），balance（余额）；
     *
     * */
    public function tpl_cz_mesg($arr)
    {
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $map['id'] = $CardMember->where('card_id', $arr['card_id'])->value('mid');
        $wx_open_id = $Merchant->where($map)->value('wx_open_id');
        //初始化微信类
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mid = $this->getmid($arr['card_id']);
        $map['id'] = $mid;
        $merchantiinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantiinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantiinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $wxObj = new Wxobjopen($options);
        $OpenTemplate = new OpenTemplate();
        $templateid = $OpenTemplate->where(['type' => 'card_ye_tpl', 'wx_open_id' => $wx_open_id])->value('template_id');
        switch ($arr['type']) {
            case "1":
                $type = "充值";
                break;
            case "2":
                $type = "消费";
                break;
            default:
                $type = "未知";
                break;
        }
        $add_balance = floor($arr['add_balance'] * 100) / 100;
        $balance = floor($arr['balance'] * 100) / 100;
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => trim($templateid),
            'url' => "",
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => '余额' . $type . "提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'keyword2' => ['value' => '余额' . $type, 'color' => '#FF0000'],
                'keyword3' => ['value' => $add_balance . '元', 'color' => '#000'],
                'keyword4' => ['value' => $balance . '元', 'color' => '#000'],
                'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
            )
        );
        $res = $wxObj->sendTemplateMessage($template);
        if ($res['errcode'] == 0) {
            $CardUserGet = new CardUserGet();
            $arrp['card_id'] = $arr['card_id'];
            $arrp['code'] = $CardUserGet->where(['openid' => $arr['openid'], 'card_id' => $arr['card_id']])->value('code');
            $arrp['price'] = $balance;
            $resu = $this->updateprice($arrp);
            $rarr = $resu;
        } else {
            $rarr = $res;
        }
        return $rarr;
    }

    //余额更新
    public function updateprice($arr)
    {
        //实例化微信
        $options = $this->options($arr['card_id']);
        $WxObj = new Wxobjopen($options);
        $data = [
            'code' => $arr['code'],
            'card_id' => $arr['card_id'],
            'custom_field_value2' => $arr['price'] . '元',
            'notify_optional' => [
                'is_notify_bonus' => false,
                'is_notify_balance' => false,
                'is_notify_custom_field2' => false,
            ],
        ];
        $res = $WxObj->updateUserInfo($data);
        return $res;
    }

    //积分更新
    public function updatebonus($arr)
    {

        //实例化微信
        //初始化微信类
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mid = $this->getmid($arr['card_id']);
        $map['id'] = $mid;
        $merchantiinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantiinfo['wx_open_id'];
        $config = $Agent->where(array('id' => $merchantiinfo['agent']))->find();
//        $config = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $WxObj = new Wxobjopen($options);
        $data = [
            'code' => $arr['code'],
            'card_id' => $arr['card_id'],
            'record_bonus' => $arr['record_bonus'],
            'add_bonus' => $arr['add_bonus'],
            'notify_optional' => [
                'is_notify_bonus' => true,
                'is_notify_balance' => true,
                'is_notify_custom_field1' => true,
            ],
        ];
        $res = $WxObj->updateUserInfo($data);
        return $res;
    }

    //充值赠送卡券
    public function tpl_zs_mesg($arr)
    {
        $System = new System();
        $WxOpen = new WxOpen();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $mid = $this->getmid($arr['card_id']);
        $map['id'] = $mid;
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $weObj = new Wxobjopen($options);
        //模板ID
        $OpenTemplate = new OpenTemplate();
        $templateid = $OpenTemplate->where(['type' => 'card_zs_tpl', 'wx_open_id' => $mab['id']])->value('template_id');
        $Platurl = new Platurl();
        $agent_url = $Platurl->getagenturl('card_id', $arr['card_id']);
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => $templateid,
            'url' => $agent_url . "/mobile.php/carduser/addcard/card_id/" . $arr['card_id'] . "/openid/" . $arr['openid'],
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => "卡券赠送提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => $arr['name'], 'color' => '#000'],
                'keyword2' => ['value' => $arr['title'], 'color' => '#FF0000'],
                'keyword3' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
            )
        );
        $res = $weObj->sendTemplateMessage($template);
        return $res;
    }

    //获取代理商域名
//    public function getagenturl($card_id){
//        $CardMember = new CardMember();
//        $Merchant = new Merchant();
//        $Agent=new Agent();
//        $mid = $CardMember->where('card_id', $card_id)->value('mid');
//        $agent_id = $Merchant->where(['id'=>$mid])->value('agent');
//        $agent_url = $Agent->where(['id'=>$agent_id])->value('open_url');
//        return 'https://'.$agent_url;
//    }


    //充值赠送卡券
    public function tpl_zs_mesg_list($arr)
    {
        $System = new System();
        $WxOpen = new WxOpen();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $mid = $this->getmid($arr['card_id']);
        $map['id'] = $mid;
        $merchantiinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantiinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantiinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $weObj = new Wxobjopen($options);
        //模板ID
        $OpenTemplate = new OpenTemplate();
        $templateid = $OpenTemplate->where(['type' => 'card_zs_tpl', 'wx_open_id' => $mab['id']])->value('template_id');
        $Platurl = new Platurl();
        $agent_url = $Platurl->getagenturl('card_id', $arr['card_id']);
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => $templateid,
            'url' => $agent_url . "/mobile.php/carduser/addcardlist/openid/" . $arr['openid'] . "/give/" . $arr['give'] . '/card_id/' . $arr['card_id'],
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => "卡券赠送提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => $arr['name'], 'color' => '#000'],
                'keyword2' => ['value' => $arr['title'], 'color' => '#FF0000'],
                'keyword3' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
            )
        );
        $res = $weObj->sendTemplateMessage($template);
        return $res;
    }


    //根据card_id获取Mid
    public function getmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }


    public function orderinfo()
    {
        $request = request();
        //广告
        $Adview = new Adview();
        $ad_type = $Adview->getadtype($request->param('orderid'));
//        file_put_contents('/data2/html/payos/payad.txt', json_encode($ad_type), 8);
        if ($ad_type['ad_type'] == '1') {
            $Adview->getadvert($request->param('orderid'));
        }


        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $System = new System();

        $map['id'] = $request->param('id');
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
//        $config2 = $System->where(array('id' => 1))->find();
        $options = array(
            'component_token' => $agent['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $agent['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $agent['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $agent['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $agent['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );

        $weObj = new Wxobjopen($options);
        $openid = session('openid');
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Wxpaynocardpay/orderinfo", array('id' => $request->param('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {

                $openid = $info['openid'];

            }
        }
        $maq['orderid'] = $request->param('orderid');

        $Paylog = new Paylog();
        $order = $Paylog->where($maq)->find();
        $order['deduzkinfo'] = "";
        if ($openid == $order['openid']) {

            $mav['id'] = $request->param('id');
            $Merchant = new Merchant();
            $shmc = $Merchant->where($mav)->value('merchant');


            $this->assign('shmc', $shmc);
            $this->assign('order', $order);
            $this->assign('id', $request->param('id'));
            $this->assign('orderid', $request->param('orderid'));
        } else {
            $this->error('非订单支付者无法查看订单详情');
        }
        //jssdk
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $jssdk = $weObj->getJsSign($url);
        $this->assign('jssdk', $jssdk);
        $this->assign('jssdk', $jssdk);
        return $this->fetch('index/orderinfo');
    }

    public function get_user_info($openid = 'ok2ajuAJm7owX6UaYGoQZ05YFcww', $id = 1)
    {
        $us['openid'] = $openid;
        $Wxuser = new WxUser();
        $user = $Wxuser->where("openid='$openid'")->count();
        if ($user == 0) {
            $map['id'] = $id;
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $System = new System();
            $user = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $user['agent']))->find();
//            $config = $System->where(array('id' => 1))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $options = array(
                'component_token' => $agent['component_token'], // 填写你设定的key
                'component_encodingaeskey' => $agent['component_encodingaeskey'], // 填写加密用的EncodingAESKey
                'component_appid' => $agent['component_appid'], // 填写高级调用功能的app id
                'component_appsecret' => $agent['component_appsecret'], // 填写高级调用功能的密钥
                'open_ticket' => $agent['open_ticket'],
                'authorizer_appid' => $users['authorizer_appid'],
                'authorizer_refresh_token' => $users['authorizer_refresh_token'],
            );
            $weObj = new Wxobjopen ($options);
            $userinfo = $weObj->getUserInfo($openid);
            $userinfo = json_encode($userinfo);


            $data['openid'] = $openid;
            $data['wx_info'] = $userinfo;
            $data['addtime'] = time();
            $add = $Wxuser->save($data);

        }
    }

    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        //  Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}